﻿using Microsoft.AspNetCore.SignalR.Client;

namespace SingalR.Client
{
    public static class SingalrMethod
    {
       static  string SignalR_Port = Environment.GetEnvironmentVariable("SignalR_Port", EnvironmentVariableTarget.Machine);//ipconfig为电脑环境变量名
        public static async Task<Tuple<string,HubConnection>> GetConnectionAsync()
        {
            try
            {
                HubConnection connection = new HubConnectionBuilder().
                    WithUrl(SignalR_Port).Build();//http://localhost:5198/chat
                //连接
                await connection.StartAsync();
                await connection.SendAsync("CallOtherClients", "我是api");
              
                return Tuple.Create("连接正常", connection);
            }
            catch(Exception ex)
            {
                return Tuple.Create<string, HubConnection?>("连接正常", null);
            }
    
            
     
        }
        public static async Task<HubConnection> GetConnectionToWmsAsync()
        {  
            HubConnection connection = new HubConnectionBuilder().
            WithUrl(SignalR_Port).Build();//http://localhost:5198/chat

            //断线重连
            connection.Closed += async (Exception? error) =>
            {
                await Task.Delay(new Random().Next(0, 2) * 1000);
                await connection.StartAsync();
            };
            //连接
            await connection.StartAsync();
            await connection.SendAsync("CallOtherClients", "我是wms");
            return connection;
        }

    }
}
